package com.cmc.cloud.cmclink.doc.controller.admin.special;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.DgProhibitedErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.convert.DgProhibitedConvert;
import com.cmc.cloud.cmclink.doc.convert.DgProhibitedItemConvert;
import com.cmc.cloud.cmclink.doc.dto.DgProhibitedGetDto;
import com.cmc.cloud.cmclink.doc.entity.DgProhibitedCountDO;
import com.cmc.cloud.cmclink.doc.entity.DgProhibitedDO;
import com.cmc.cloud.cmclink.doc.entity.DgProhibitedWithSubDO;
import com.cmc.cloud.cmclink.doc.service.DgProhibitedItemService;
import com.cmc.cloud.cmclink.doc.service.DgProhibitedService;
import com.cmc.cloud.cmclink.doc.vo.special.dgprohibiteditemvo.DgProhibitedItemRespVO;
import com.cmc.cloud.cmclink.doc.vo.special.dgprohibitedvo.*;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.excel.core.util.ExcelUtils;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 危险品禁接清单前端接口Controller
 * 
 * @author codegen
 */
@Slf4j
@Tag(name = "管理后台 - 危险品禁接清单")
@RestController
@Validated
@RequestMapping(UrlConstants.APPLICATION_URL + "/special/dg-prohibited")
public class DgProhibitedController {

    @Resource
    private DgProhibitedService dgProhibitedService;

    @Resource
    private DgProhibitedItemService dgProhibitedItemService;

    @Operation(summary = "创建危险品禁接清单")
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermission('doc:prohibited:create')")
    public CommonResult<Void> createDgProhibited(@Valid @RequestBody DgProhibitedCreateReqVO createReqVO) {
        dgProhibitedService.createDgProhibited(createReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "更新危险品禁接清单")
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermission('doc:prohibited:edit')")
    public CommonResult<Void> updateDgProhibited(@Valid @RequestBody DgProhibitedUpdateReqVO updateReqVO) {
        dgProhibitedService.updateDgProhibited(updateReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "删除危险品禁接清单")
    @PostMapping("/delete/{id}")
    @Parameter(name = "id", description = "主键ID", required = true)
    @PreAuthorize("@ss.hasPermission('doc:prohibited:delete')")
    public CommonResult<Void> deleteDgProhibited(@PathVariable("id") Long id) {
        dgProhibitedService.deleteDgProhibited(id);
        return CommonResult.success();
    }

    @Operation(summary = "获得危险品禁接清单")
    @GetMapping("/get/{id}")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @UseResponsePropertyAdvice
    public CommonResult<DgProhibitedRespVO> getDgProhibited(@PathVariable("id") Long id) {
        DgProhibitedGetDto dgProhibitedGetDto = dgProhibitedService.getDgProhibited(id);
        DgProhibitedRespVO respVO = DgProhibitedConvert.INSTANCE.convert(dgProhibitedGetDto.getDgProhibitedDO());
        List<DgProhibitedItemRespVO> itemRespVO =
            DgProhibitedItemConvert.INSTANCE.convertVOList(dgProhibitedGetDto.getDgProhibitedItemsDO());
        respVO.setDgProhibitedItemRespVOList(itemRespVO);
        return CommonResult.success(respVO);
    }

    @Operation(summary = "获得危险品禁接清单分页")
    @PostMapping("/page")
    @UseResponsePropertyAdvice
    @PreAuthorize("@ss.hasPermission('doc:prohibited:search')")
    public CommonResult<PageResult<DgProhibitedRespVO>>
        getDgProhibitedPage(@Valid @RequestBody DgProhibitedPageReqVO pageVO) {
        PageResult<DgProhibitedDO> pageResult = dgProhibitedService.getDgProhibitedPage(pageVO);
        List<DgProhibitedRespVO> results = DgProhibitedConvert.INSTANCE.convertList(pageResult.getList());
        List<Long> mainIds = results.stream().map(DgProhibitedRespVO::getId).collect(Collectors.toList());
        List<DgProhibitedCountDO> countDOList = dgProhibitedItemService.getCountByMainIdList(mainIds);
        results.forEach(result -> countDOList.forEach(countDO -> {
            if (result.getId().equals(countDO.getMainId())) {
                result.setDetails(countDO.getDetails());
            }
        }));
        return CommonResult.success(new PageResult<>(results, pageResult.getTotal()));
    }

    @GetMapping("/excel-export")
    @Operation(summary = "excel导出")
    @PreAuthorize("@ss.hasPermission('doc:prohibited:export')")
    public void exportExcel(HttpServletResponse response, @RequestParam("listType") String listType,
        @RequestParam("codeType") String codeType, @RequestParam("codeValue") String codeValue) throws IOException {
        DgProhibitedExcelReqVO excelReqVO = new DgProhibitedExcelReqVO();
        excelReqVO.setListType(listType);
        excelReqVO.setCodeType(codeType);
        excelReqVO.setCodeValue(codeValue);
        List<DgProhibitedWithSubDO> dgProhibitedWithSubsDO;
        try {
            dgProhibitedWithSubsDO = dgProhibitedService.getDgProhibitedWithSubList(excelReqVO);
        } catch (Exception e) {
            log.error("导出数据表失败", e);
            throw ServiceExceptionUtil.exception(DgProhibitedErrorCodeConstants.DG_PROHIBITED_EXPORT_FAILED);
        }
        List<DgProhibitedExcelVO> exportList = DgProhibitedConvert.INSTANCE.convertExcelList(dgProhibitedWithSubsDO);

        // 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        response.addHeader("Content-Disposition",
            "attachment;filename=" + URLEncoder.encode("危险品紧接清单详情.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "maintain_dg_prohibited.xls", "maintain", DgProhibitedExcelVO.class, exportList);
    }

    @Operation(summary = "批量更新危险品禁接清单失效时间")
    @GetMapping("/update/endDate")
    @Parameter(name = "ids", description = "id列表", required = true, example = "1024,2048")
    @Parameter(name = "endDate", description = "结束日期", required = true, example = "2020-01-01")
    @PreAuthorize("@ss.hasPermission('doc:prohibited:batchEdit')")
    public CommonResult<Void> updateEndDates(@RequestParam("ids") List<Long> ids,
        @RequestParam("endDate") LocalDate endDate) {
        dgProhibitedService.updateEndDates(ids, endDate);
        return CommonResult.success();
    }
}
